<?

class Mdl_Users extends MY_Model {

    function Mdl_Users() {

        parent::MY_Model();

        $this->limit = 25;

    }

    function get($params = NULL) {

        $this->prep_params($params);

        if (isset($params['user_id'])) {

        // make sure the proper meta keys exist
            $this->meta_update($params['user_id']);

            $this->db->where('user_id', $params['user_id']);

        }

        if (isset($params['paginate']) AND $params['paginate'] == TRUE) {

            $offset = ($this->page * $this->limit) - $this->limit;

            $this->db->limit($this->limit, $offset);

        }

        // do not list global administrator if current user is less than global administrator

        if ($this->session->userdata('user_type_id') == 1) {

            $this->db->where('(inktype_users.site_id', $this->session->userdata('site_id'));

            $this->db->or_where('inktype_users.user_type_id = 1)');

        }

        else {

            $this->db->where('inktype_users.site_id', $this->session->userdata('site_id'));

        }

        $query = $this->db->get('inktype_users');

        if (isset($params['paginate']) AND $params['paginate'] == TRUE) {

            $this->set_page_links();

        }

        if (isset($params['user_id'])) {

            $meta = $this->get_meta($query->row()->user_id);

            $user = $query->row();

            foreach ($meta as $key=>$value) {

                $user->$key = $value;

            }

            return $user;

        }

        else {

            return $query->result();

        }

    }

    function get_authors() {

        $this->db->where('inktype_users.user_type_id = 1 OR inktype_users.user_type_id = 3 OR ((user_type_id = 2 OR user_type_id = 4) AND site_id = ' . $this->session->userdata('site_id') . ')');

        $query = $this->db->get('inktype_users');

        return $query->result();

    }

    function get_num_users() {

        $this->db->select('COUNT(*) AS num_users');

        $this->db->where('site_id', $this->session->userdata('site_id'));

        $query = $this->db->get('inktype_users');

        $result = $query->row();

        return $result->num_users;

    }

    function get_meta($user_id) {

    // retrieve the meta fields and assign to meta_{$meta_key}
        $this->db->where('user_id', $user_id);

        $query = $this->db->get('inktype_user_meta');

        foreach ($query->result() as $user_meta) {

            $result_key = 'meta_' . $user_meta->meta_key;

            $result->{$result_key} = $user_meta->meta_value;

        }

        return $result;

    }

    function prep_meta_validation($user_id) {

        $this->db->where('user_id', $user_id);

        $query = $this->db->get('inktype_user_meta');

        foreach ($query->result() as $result) {

            $meta_key = 'meta_' . $result->meta_key;

            $this->validation->$meta_key = $result->meta_value;

        }

    }

    function save() {

        $db_array = $this->prep_db_array();

        if ($this->is_admin) {

            $db_array['site_id'] = $this->session->userdata('site_id');

        }

        else {

            $db_array['site_id'] = $this->inktype->site_id;

        }

        foreach (array_keys($this->_meta_keys()) as $meta_key) {

            unset($db_array['meta_' . $meta_key]);

        }

        if (!$this->input->post('user_type_id')) {

            $db_array['user_type_id'] = 99;

        }

        if (!$this->input->post('password')) {

            unset ($db_array['password']);

        }

        unset($db_array['passwordv']);

        if (!isset($this->uri_assoc['user_id'])) {

            $db_array['date_registered'] = time();

            $this->db->insert('inktype_users', $db_array);

            // insert the proper default meta keys and values for this user
            $this->meta_update($this->db->insert_id());

        }

        else {

            $this->db->where('user_id', $this->uri_assoc['user_id']);

            $this->db->update('inktype_users', $db_array);

            // save the meta values from the user form
            foreach (array_keys($this->_meta_keys()) as $meta_key) {

                $db_array = array(
                    'meta_value'	=>	$this->input->post('meta_' . $meta_key));

                $this->db->where('meta_key', $meta_key);

                $this->db->where('user_id', $this->uri_assoc['user_id']);

                $this->db->update('inktype_user_meta', $db_array);

            }

            // if the user is currently logged in, update their session data
            if ($this->session->userdata('user_id') == $this->uri_assoc['user_id']) {

                $user = $this->get(array('user_id'=>$this->session->userdata('user_id')));

                unset ($user->password, $user->site_id);

                $this->session->set_userdata($user);

            }

        }

        $this->session->set_flashdata('success_save', TRUE);

    }

    function delete() {

        if (isset($this->uri_assoc['user_id'])) {

            $this->db->where('user_id', $this->uri_assoc['user_id']);

            $this->db->delete('inktype_users');

            $this->session->set_flashdata('success_delete', TRUE);

        }

    }

    function validate() {

        $this->fields = array(
            'email_address'         =>  'Email Address',
            'display_name'          =>  'Display Name',
            'password'              =>  'Password',
            'website_url'           =>  'Website URL',
            'user_type_id'          =>  'User Type',
            'meta_content_editor'   =>  'Content Editor'
        );

        $this->rules = array(
            'email_address' =>  'required|valid_email',
            'display_name'  =>  'required'
        );

        if (!isset($this->uri_assoc['user_id'])) {

            $this->rules['password'] = 'required|matches[passwordv]|md5';

        }

        else {

            $this->rules['password'] = 'matches[passwordv]|md5';

        }

        return $this->_validate();

    }

    function validate_register() {

        $this->fields = array(
            'email_address' =>  'Email Address',
            'display_name'  =>  'Display Name',
            'password'      =>  'Password',
            'passwordv'     =>  'Password Verification',
            'user_level'    =>  'User Level'
        );

        $this->rules = array(
            'email_address' =>  'required|valid_email',
            'display_name'  =>  'required',
            'password'      =>  'required|md5',
            'passwordv'     =>  'required|md5'
        );

        if ($this->_validate() AND $this->_email_is_unique($this->input->post('email_address')) AND $this->_display_name_is_unique($this->input->post('display_name'))) {

            $this->save();

            redirect($this->inktype->site_url_title . '/' . $this->input->post('redirect'));

        }

    }

    function _meta_keys() {

        return array(
        'content_editor'	=>	1);

    }

    function meta_update($user_id) {

        $meta_keys = $this->_meta_keys();

        foreach ($meta_keys as $key=>$value) {

            $this->db->where('user_id', $user_id);

            $this->db->where('meta_key', $key);

            $query = $this->db->get('inktype_user_meta');

            if (!$query->num_rows()) {

                $db_array = array(
                    'user_id'       =>  $user_id,
                    'meta_key'      =>  $key,
                    'meta_value'    =>  $value
                );

                $this->db->insert('inktype_user_meta', $db_array);

            }

        }

    }

    function _email_is_unique($email_address) {

        $this->db->where('email_address', $email_address);

        $query = $this->db->get('inktype_users');

        if ($query->num_rows()) {

            $this->validation->error_string = '<p>The Email Address you entered is already in use. Please try again.</p>';

            return FALSE;

        }

        else {

            return TRUE;

        }

    }

    function _display_name_is_unique($display_name) {

        $this->db->where('display_name', $display_name);

        $query = $this->db->get('inktype_users');

        if ($query->num_rows()) {

            $this->validation->error_string = '<p>The Display Name you entered is already in use. Please try again.</p>';

            return FALSE;

        }

        else {

            return TRUE;

        }

    }

}

?>